<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Test</title>
</head>
<body>
<h1>Hello</h1>

<br/>

<input type="checkbox" name="moneyLock" id="moneyLock" >
<label>锁定金钱</label>
<div >剩余金钱: </div>
<div id="moneyRemaining">剩余金钱</div>

<br/>
<br/>
<br/>
<input type="text" id="liveRoomToken" placeholder="直播间token，测试可不写">
<button onclick="regist()">1直播间token登录</button>

<input type="text" id="liveRoomId" placeholder="先填写直播间id">

<br/>

<button onclick="startGame()">2为直播间开始游戏</button>

<br/>
<br/>

<input type="text" id="userId" placeholder="用户ID">
<input type="text" id="userName" placeholder="用户名">
<input type="text" id="jobName" placeholder="战士法师道士，可不填">







<br/>

<button onclick="sendJoinMsg(1)">3选择1号摩托</button>
<button onclick="sendJoinMsg(2)">3选择2号摩托</button>
<button onclick="sendJoinMsg(3)">3选择3号摩托</button>

<br/>
<input type="text" id="giftNum" placeholder="礼物数量">礼物数量
<br/>

<button onclick="sendLikeMsg()">送点赞礼物</button>
<button onclick="sendJoinMsg(666)">送666礼物</button>
<button onclick="sendJoinMsg(666666)">送666666礼物</button>
<button onclick="sendOneGiftMsg(2)">送礼物-魔法棒</button>
<button onclick="sendOneGiftMsg(3)">送礼物-药丸-</button>
<button onclick="sendOneGiftMsg(13)">送礼物-魔法镜</button>
<button onclick="sendOneGiftMsg(5)">送礼物-电池</button>
<button onclick="sendOneGiftMsg(6)">送礼物-炸弹</button>
<button onclick="sendOneGiftMsg(7)">送礼物-空投</button>
<button onclick="sendOneGiftMsg(11)">粉丝团-加入</button>
<button onclick="sendOneGiftMsg(12)">粉丝团-升级</button>

<br/>
<br/>

<button onclick="endGame()">5为直播间结束游戏</button>

<button onclick="closeSendManyRequest()">关闭批量请求</button>

<br/>
<br/>

<div id="consoleText">信息板</div>

<br/>
<br/>
<br/>

<button onclick="sendAnchorLoginRequst()">发送token请求</button>

<br/>
<br/>
<br/>

<button onclick="sendPingLunRequest()">发送评论数据</button>

<!--<br/>-->
<!--<br/>-->
<!--<br/>-->

<!--<button onclick="sendGiftRequest()">发送批量礼物数据</button>-->

<br/>
<br/>
<br/>

<button onclick="sendFinishRequest()">发送完赛数据</button>
<br/>
<br/>
<br/>

<button onclick="sendGetWorldRecordsRequest()">获取世界记录</button>
<br/>
<br/>
<br/>

<button onclick="openSendManyRequest()">开启批量请求</button>

<br/>
<br/>
<br/>

<button onclick="openSendManyZanRequest()">开启批量请求（仅有赞）</button>

<br/>
<br/>
<br/>

<button onclick="closeSendManyRequest()">关闭批量请求</button>

<br/>
<br/>
<br/>

<button onclick="sendClientErrorRequest()">测试客户端报错请求</button>
<br/>
<br/>
<input type="text" id="gameData" placeholder="直播间数据，结果最好是json">
<br/>
<br/>

<button onclick="sendGameData()">发送直播间数据</button>
<br/>

<button onclick="getGameData()">获取最新直播间数据</button>
<br/><br/>
<button onclick="closeConnection()">一键断线</button>
<br/><br/>
<input type="text" id="backTimestamp" placeholder="毫秒时间戳,补发用">
<button onclick="backRegist()">补发重连登录</button>


<script>
    var ws = null;
    var wsIsClose = null;
    var joinedTrack = null;
    var liveRoomID = "11111"
    var userId = ""
    var consoleMessageArray = []
    var wsRequestMethod = "ws"
    var httpRequestMethod = "http"
    var ip = "82.157.179.66:8001"
    var moneyRemaining = 3000
    // 直播间登录给的token
    var liveRoomToken = ""
    // 后台生成的用来登录态请求的token
    var liveRoomAuthToken = ""
    // var ip = "localhost"

    setMonyRemainingText(moneyRemaining)

    var headImgArr = [
            "https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",
            "https://blaze-api-test.xinghuohuiju.com/static/16e1041e5e02db1c77678084102a9b6b.jpeg",
            "https://blaze-api-test.xinghuohuiju.com/static/8944face68cc71bc452ea8a4fd0abc5b.jpeg",
            "https://blaze-api-test.xinghuohuiju.com/static/9c19c581f33e134b252d44dbc5ddef67.jpg",
            "https://blaze-api-test.xinghuohuiju.com/static/1a59df123cac3944d1104dd164160888.jpeg",
            "https://blaze-api-test.xinghuohuiju.com/static/d5ade3fccf97e1fc59ba2c7c63619cf9.jpg",
            "https://blaze-api-test.xinghuohuiju.com/static/a45f096821bb09659443c512c204ec47.jpeg",
            "https://blaze-api-test.xinghuohuiju.com/static/391b8b23c018e957d38b6787f0791fa7.jpeg",
    ]

    var headImg = headImgArr[Math.floor(Math.random() * (headImgArr.length - 1))];

    function getQueryParams() {
        var queryParams = {};
        var queryString = window.location.search.substring(1); // 移除开头的'?'
        var pairs = queryString.split("&");
        for (var i = 0; i < pairs.length; i++) {
            var pair = pairs[i].split("=");
            if (pair.length === 2) {
                queryParams[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
            }
        }
        return queryParams;
    }

    var queryParams = getQueryParams();
    var local = queryParams.local === '1'; // 检查是否有local=1参数
    if(local){
        ip = "localhost:8001"
    }

    var prod = queryParams.prod === '1'; // 检查是否有local=1参数
    if(prod){
        ip = ip.replaceAll(":8001", ":8011")
    }

    var isHttps = queryParams.https === '1'; // 检查是否有local=1参数
    if(isHttps){
        wsRequestMethod = "wss"
        httpRequestMethod = "https"
    }

    var settingHostName = queryParams.host ; // 检查是否有local=1参数

    console.log("queryParams.host : ", queryParams.host)

    if(settingHostName){
        ip = settingHostName
        console.log("set ip : ", ip)
    }


    var giftList = [
        {
            id: 1,
            giftId : "1",
            name: "点赞",
            value: 0,
        },
        {
            id: 11,
            giftId : "2",
            name: "加入粉丝团",
            value: 0,
        },
        {
            id: 12,
            giftId : "3",
            name: "粉丝团升级",
            value: 0,
        },
        {
            id: 2,
            giftId : "n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",
            name: "仙女棒",
            value: 10,
        },
        {
            id: 3,
            giftId : "28rYzVFNyXEXFC8HI+f/WG+I7a6lfl3OyZZjUS+CVuwCgYZrPrUdytGHu0c=",
            name: "能力药丸",
            value: 100,
        },
        {
            id: 13,
            giftId : "fJs8HKQ0xlPRixn8JAUiL2gFRiLD9S6IFCFdvZODSnhyo9YN8q7xUuVVyZI=",
            name: "魔法镜",
            value: 190,
        },
        {
            id: 4,
            giftId : "PJ0FFeaDzXUreuUBZH6Hs+b56Jh0tQjrq0bIrrlZmv13GSAL9Q1hf59fjGk=",
            name: "甜甜圈",
            value: 520,
        },
        {
            id: 5,
            giftId : "IkkadLfz7O/a5UR45p/OOCCG6ewAWVbsuzR/Z+v1v76CBU+mTG/wPjqdpfg=",
            name: "能量电池",
            value: 990,
        },
        {
            id: 6,
            giftId : "gx7pmjQfhBaDOG2XkWI2peZ66YFWkCWRjZXpTqb23O/epru+sxWyTV/3Ufs=",
            name: "爱的爆炸",
            value: 1990,
        },
        {
            id: 7,
            giftId : "pGLo7HKNk1i4djkicmJXf6iWEyd+pfPBjbsHmd3WcX0Ierm2UdnRR7UINvI=",
            name: "神秘空投",
            value: 5200,
        }
    ]

    function getGiftData(giftId){
        for(let i=0;i<giftList.length;i++){
            if(giftList[i].id === giftId){
                return giftList[i]
            }
        }
    }

    function regist() {
        // liveRoomID = document.getElementById('liveRoomId').value;
        liveRoomToken = document.getElementById('liveRoomToken').value;
        // if(liveRoomID===''){
        //     alert("请输入您的直播间号")
        //     return
        // }
        if(liveRoomToken===''){
            liveRoomToken = "this@is*Test"
        }

        liveRoomToken = encodeURIComponent(liveRoomToken)

        var url = wsRequestMethod + "://" + ip + "/index/regist?" + "liveRoomToken=" + liveRoomToken;
        console.log("connect ws url : ", url)
        useConnection(url)
        if (ws.readyState === WebSocket.OPEN) {
            ws.send("hello server,I am client");
        } else {
            consoleText("WebSocket 连接未打开");
        }
    }

    function backRegist() {
        // liveRoomID = document.getElementById('liveRoomId').value;
        liveRoomToken = document.getElementById('liveRoomToken').value;
        // if(liveRoomID===''){
        //     alert("请输入您的直播间号")
        //     return
        // }
        if(liveRoomToken===''){
            liveRoomToken = "this@is*Test"
        }

        liveRoomToken = encodeURIComponent(liveRoomToken)

        var url = wsRequestMethod + "://" + ip + "/index/regist?" + "liveRoomToken=" + liveRoomToken;
        backDataByTime = document.getElementById('backTimestamp').value;
        if(backDataByTime===''){
            alert("请填写一个毫秒时间戳")
            return
        }
        url = url + "&backDataByTime=" + backDataByTime
        console.log("connect ws url : ", url)
        useConnection(url)
        if (ws.readyState === WebSocket.OPEN) {
            ws.send("hello server,I am client");
        } else {
            consoleText("WebSocket 连接未打开");
        }
    }

    function startGame() {
        if(liveRoomAuthToken == ''){
            alert("登录暂未完成，请稍后")
            return
        }
        var message = {
            event: "start_game",
            auth: liveRoomAuthToken,
            message_id: generateUUID(),
            data: {
            }
        };
        ws.send(JSON.stringify(message));
    }

    function closeConnection() {
        if(liveRoomAuthToken == ''){
            alert("登录暂未完成，请稍后")
            return
        }
        var message = {
            event: "close_conn",
            auth: liveRoomAuthToken,
            message_id: generateUUID(),
            data: {
            }
        };
        ws.send(JSON.stringify(message));
    }

    function endGame() {
        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID===''){
            alert("请输入您的直播间号")
            return
        }
        if(liveRoomAuthToken == ''){
            alert("登录暂未完成，请稍后")
            return
        }
        var message = {
            event: "end_game",
            auth: liveRoomAuthToken,
            message_id: generateUUID(),
            data: {
            }
        };
        ws.send(JSON.stringify(message));
    }



    function connectWebSocket(url) {
        if (ws != null){
            ws.close(); // 关闭当前连接
        }
        ws = new WebSocket(url);
        ws.onopen = function (result){
            console.log(result);
            wsIsClose == false
            consoleText("ws打开成功");
        }
        ws.onmessage = function (result){
            console.log(result);
            console.log("接收到消息：" + result.data);
            const messages = JSON.parse(result.data);

            // 检查messages是对象还是数组
            if (Array.isArray(messages)) {
                // messages是数组，使用forEach遍历
                messages.forEach(message => {
                    handleMessage(message);
                });
            } else {
                // messages是对象，直接调用handleMessage
                handleMessage(messages);
            }
        }
        ws.onclose = function (result){
            console.log(result);
            wsIsClose = true
            consoleText("连接关闭");
        }
    }

    function useConnection(url) {
        console.log("useConnection ws : ", ws, ws == null)
        if (ws == null || wsIsClose == true){
            connectWebSocket(url);
        }
    }

    // // 连接WebSocket
    // connectWebSocket();
    function checkWs(){
        if (ws == null){
            return false
        }
        return true
    }

    function checkTrackExist(){
        if (joinedTrack == null){
            return false
        }
        return true
    }

    function sendLikeMsg() {
        if (checkTrackExist() === false){
            alert("请选择支持一个摩托车手")
            return
        }

        let userId = document.getElementById('userId').value;
        let userName = document.getElementById('userName').value;

        if(userId===''){
            alert("请输入用户id")
            return
        }

        if(userName===''){
            alert("请输入用户名")
            return
        }

        let giftNum = document.getElementById('giftNum').value;
        if(giftNum !='' && parseInt(giftNum)<=0){
            alert("礼物数量请填入数字")
            return
        }
        if(giftNum===''){
            giftNum = 1
            document.getElementById('giftNum').value = giftNum
        }
        giftNum = parseInt(giftNum)

        const url = httpRequestMethod + `://${ip}/api/v1/getLikeRequest`;

        let likeArr = [
            {
                "msg_id": generateUUID(),  // string类型id
                "sec_openid": userId,    // 评论用户的加密openid, 当前其实没有加密
                "like_num": giftNum,        // 送出的礼物数量
                "avatar_url": headImg,     // 评论用户头像
                "nickname": userName,      // 评论用户昵称(不加密)
                "timestamp": Date.now(), // 评论毫秒级时间戳
            },
        ]

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  { arr: likeArr }
        const headers = {
            'Authorization': 'Bearer ' + liveRoomToken,
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{
            console.log("send one gift res : ", res)
            consoleText("点赞消息处理成功")
        });
    }

    function sendOneGiftMsg(giftId) {
        if (checkTrackExist() === false){
            alert("请选择支持一个摩托车手")
            return
        }

        let userId = document.getElementById('userId').value;
        let userName = document.getElementById('userName').value;

        if(userId===''){
            alert("请输入用户id")
            return
        }

        if(userName===''){
            alert("请输入用户名")
            return
        }

        const url = httpRequestMethod + `://${ip}/api/v1/getGiftRequest`;

        let giftData = getGiftData(giftId)

        let giftNum = document.getElementById('giftNum').value;
        if(giftNum !='' && parseInt(giftNum)<=0){
            alert("礼物数量请填入数字")
            return
        }
        if(giftNum===''){
            giftNum = 1
            document.getElementById('giftNum').value = giftNum
        }
        giftNum = parseInt(giftNum)

        let giftArr = [
            {
                "msg_id": generateUUID(),  // string类型id
                "sec_openid": userId,    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": giftData.giftId,  // 加密的礼物id
                "gift_num": giftNum,        // 送出的礼物数量
                "gift_value": giftData.value,    // 礼物总价值，单位分
                "avatar_url": headImg,     // 评论用户头像
                "nickname": userName,      // 评论用户昵称(不加密)
                "timestamp": Date.now(), // 评论毫秒级时间戳
            },
        ]

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  { arr: giftArr }
        const headers = {
            'Authorization': 'Bearer ' + liveRoomToken,
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{
            console.log("send one gift res : ", res)
            consoleText("礼物消息处理成功")
        });
    }

    function sendOneGiftMsgByWs(giftId) {
        if (checkWs() === false){
            alert("请先加入直播间")
            return
        }
        if (checkTrackExist() === false){
            alert("请选择支持一个摩托车手")
            return
        }

        let giftData = getGiftData(giftId)
        console.log("sendOneGiftMsg giftId:", giftId)
        console.log("sendOneGiftMsg giftData:", giftData)

        var amount = 1; // 假设你要发送礼物的账号是50

        var message = {
            event: "send_gift",
            message_id: generateUUID(),
            data: {
                gift_id: giftData.giftId.toString(),
                gift_num: amount,
                gift_value: giftData.value,
                name: giftData.name,
            }
        };

        if(!doMoneyLockLogic(giftData.value)){
            alert("金钱不足")
            return
        }

        ws.send(JSON.stringify(message));
    }

    function doMoneyLockLogic(num){
        let moneyLock = document.getElementById('moneyLock').checked
        console.log("moneyLock : ", moneyLock)

        if(moneyLock){
            if((moneyRemaining - num) < 0){
                return false
            }

            moneyRemaining = moneyRemaining - num


            setMonyRemainingText(moneyRemaining)
        }

        return true
    }

    function sendJoinMsg(num) {
        if (checkWs() === false){
            alert("请先加入直播间")
            return
        }

        let userId = document.getElementById('userId').value;
        let userName = document.getElementById('userName').value;

        if(userId===''){
            alert("请输入用户id")
            return
        }

        if(userName===''){
            alert("请输入用户名")
            return
        }

        let url = httpRequestMethod + `://${ip}/api/v1/getPingLun`;
        joinedTrack = num

        let content = joinedTrack.toString()

        let jobName = document.getElementById('jobName').value;

        if(jobName===''){
        }else{
            url = httpRequestMethod + `://${ip}/api/v1/getPingLunChuanQi`;
            content = joinedTrack.toString() + ` ${jobName}`
        }




        console.log("sendJoinMsg function sendJoinMsg joinedTrack : ", joinedTrack)
        console.log("sendJoinMsg function sendJoinMsg headImg : ", headImg)

        let pinglunArr = [
            {
                "msg_id": generateUUID(),  // string类型id
                "sec_openid": userId,    // 评论用户的加密openid, 当前其实没有加密
                "content": content,       // 评论内容(加入轨道)
                "avatar_url": headImg,     // 评论用户头像
                "nickname": userName,      // 评论用户昵称(不加密)
                "timestamp": Date.now(), // 评论毫秒级时间戳
            },
        ]

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  { arr: pinglunArr }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{
            console.log("send one gift res : ", res)
            consoleText(`加入${joinedTrack}阵营成功`)
        });
    }

    function sendJoinMsgByWs(num) {
        if (checkWs() === false){
            alert("请先加入直播间")
            return
        }
        joinedTrack = num

        var message = {
            event: "join_track",
            message_id: generateUUID(),
            data: {
                content: num.toString()
            }
        };
        ws.send(JSON.stringify(message));
    }

    function handleMessage(message) {
        switch (message.event) {
            case "game_start":
                consoleText("游戏开始:", message.data);
                break;
            case "rank":
                consoleText("排行榜:", message.data);
                break;
            case 'live_comment':
                handleLiveComment(message.data);
                break;
            case 'broad_start_game':
                handleStartGame(message.data);
                break;
            case 'broad_end_game':
                handleEndGame(message.data);
                break;
            case 'broad_live_gift':
                handleLiveGift(message.data);
                break;
            case 'broad_join_track':
                handleJoinTrack(message.data);
                break;
            case 'broad_current_score':
                handleCurrentScore(message.data);
                break;
            case 'live_like':
                handleLiveLike(message.data);
                break;
            case "speaking":
                console.log("服务器讲话:", message.data);
                break;
            case "ack":
                console.log("收到服务器回信:", message.message_id);
                break;
            case "ack_token":
                console.log("收到服务器回信:", message);
                handleAckToken(message)
                break;
            case "fail":
                handleFail(message.data);
                break;
            default:
                consoleText("未知事件:", message);
        }

        // 发送ACK消息
        if(message.event === "ack"){
            return
        }
        const ackMessage = {
            event: "ack",
            auth: liveRoomAuthToken,
            data: {
                msg_id: message.data.msg_id, // 从消息中获取msg_id
            },
        };
        ws.send(JSON.stringify(ackMessage));
    }

    // 处理直播评论
    function handleLiveComment(data) {
        const liveComment = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            content: data.content,
            avatar_url: data.avatar_url,
            nickname: data.nickname,
            timestamp: data.timestamp
        };
        consoleText('收到评论 :', liveComment);
    }

    // 处理直播间开始游戏
    function handleStartGame(data) {
        const StartGameData = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            timestamp: data.timestamp
        };
        consoleText('游戏开始 :', ", 操作用户：", StartGameData.sec_openid
            , ", 开始时间：", StartGameData.timestamp);
    }

    // 处理直播间结束游戏
    function handleEndGame(data) {
        const EndGameData = {
            msg_id: data.msg_id,
            liveRoomId: data.name,
            timestamp: data.timestamp
        };
        console.log("handleEndGame ", data)
        consoleText('游戏结束 :', ", 直播间：", EndGameData.liveRoomId
            , ", 时间：", EndGameData.timestamp);
    }

    // 处理直播间结束游戏
    function handleAckToken(data) {
        // const failData = {
        //     msg_id: data.msg_id,
        //     sec_openid: data.sec_openid,
        //     content: data.content,
        //     timestamp: data.timestamp
        // };
        console.log("ack token:", data)
        liveRoomAuthToken = data.data.token
        let liveRoomId = data.data.room_id
        document.getElementById('liveRoomId').value = liveRoomId
        consoleText('直播间登陆成功，获得登录token :', liveRoomAuthToken);
    }
    // 处理直播间结束游戏
    function handleFail(data) {
        const failData = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            content: data.content,
            timestamp: data.timestamp
        };
        console.log("failData:", failData)
        consoleText('请求出错 :', failData.content);
    }

    // 处理直播礼物
    function handleLiveGift(data) {
        const liveGift = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            sec_gift_id: data.sec_gift_id,
            gift_num: data.gift_num,
            track: data.camp,
            job: data.job,
            acc_gift_score: data.acc_gift_score,
            gift_value: data.gift_value,
            acc_gift_value: data.acc_gift_value,
            name: data.name,
            avatar_url: data.avatar_url,
            nickname: data.nickname,
            gift_level: data.gift_level,
            gift_upgrading: data.gift_upgrading,
            game_score: data.game_score,
            timestamp: data.timestamp
        };

        console.log("handleLiveGift data : ", data)

        consoleText('收到礼物 :', liveGift.name
            , ' 礼物等级 :', liveGift.gift_level, ' 礼物此次解锁 :', liveGift.gift_upgrading
            , ", 赠送用户：", liveGift.sec_openid, ' 累积礼物积分 :', liveGift.acc_gift_score
            , ", 所属阵营：", liveGift.track, ", 所属职业：", liveGift.job, ' 当前对局积分 :', liveGift.game_score);
    }

    // 处理用户加入直播间的阵营
    function handleJoinTrack(data) {
        const JoinTrackEvent = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            sec_gift_id: data.sec_gift_id,
            content: data.content,
            camp: data.camp,
            job: data.job,
            gift_num: data.gift_num,
            gift_value: data.gift_value,
            avatar_url: data.avatar_url,
            nickname: data.nickname,
            timestamp: data.timestamp
        };
        consoleText('有用户 :', JoinTrackEvent.nickname, "(", JoinTrackEvent.sec_openid, ")，加入摩托:", JoinTrackEvent.camp, "，选择职业:", JoinTrackEvent.job);
    }

    // 处理用户加入直播间
    function handleCurrentScore(data) {
        const currentScoreData = {
            msg_id: data.msg_id,
            score: data.score,
            timestamp: data.timestamp
        };
        consoleText('当前分数更新 :', currentScoreData.score, "，通知时间:", currentScoreData.timestamp);
    }

    // 处理直播点赞
    function handleLiveLike(data) {
        const liveLike = {
            msg_id: data.msg_id,
            sec_openid: data.sec_openid,
            like_num: data.like_num,
            avatar_url: data.avatar_url,
            nickname: data.nickname,
            timestamp: data.timestamp
        };
        consoleText('收到点赞 :', liveLike);
    }

    // 简单的UUID生成函数
    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    function consoleText(...args){
        // 将所有参数转换为字符串
        const messages = args.map(arg => arg.toString());
        console.log(...args)
        console.log("messages : ", messages)
        let messageStr = messages.join("")

        // 将新的消息添加到数组中，并保持数组长度为3
        consoleMessageArray = consoleMessageArray.concat([messageStr, "<br/>"]).slice(-8);

        // 将当前数组中的所有消息合并为一个字符串，并添加到累加器字符串中
        let str = consoleMessageArray.join(' ') + '\n';

        document.getElementById('consoleText').innerHTML = str
        console.log(...args)
    }

    function setMonyRemainingText(num){
        document.getElementById('moneyRemaining').innerHTML = num
    }

    function sendTokenRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/getToken`;
        const params = { userId: 'david' };
        const headers = { 'Authorization': 'Bearer your-token' };

        sendGetRequest(url, params, headers);

        // const url = 'https://api.example.com/submit';
        // const data = { name: 'John', age: 30 };
        // const headers = { 'Content-Type': 'application/json' };
        //
        // sendPostRequest(url, data, headers);
    }

    function sendAnchorLoginRequst(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/anchor/login`;
        const params = { token: 'david-token-test' };
        // const headers = { 'Authorization': 'Bearer your-token' };

        sendPostRequest(url, params)

    }

    // 选取数组随机数量个随机元素
    function getRandomSubsetUnique(arr) {
        if (arr.length === 0) return [];

        // 随机决定取出的元素数量（至少1个，最多全部）
        const randomCount = Math.floor(Math.random() * arr.length) + 1;

        // 创建一个新数组来存储随机元素
        const result = [];
        const shuffledArr = [...arr].sort(() => Math.random() - 0.5); // 打乱数组顺序

        for (let i = 0; i < randomCount; i++) {
            result.push(shuffledArr[i]);
        }

        return result;
    }


    function sendPingLunRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/getPingLun`;

        let pinglunArr = [
            {
                "msg_id": "123456781",  // string类型id
                "sec_openid":"kjabfjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "content":"1",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"yihao",      // 评论用户昵称(不加密)
                "timestamp":1649068664, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "1234aegaeg1",  // string类型id
                "sec_openid":"kjabfjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "content":"2",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"yihao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "1aegaegfafaegaeg1",  // string类型id
                "sec_openid":"aaaaafjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "content":"2",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/9c19c581f33e134b252d44dbc5ddef67.jpeg",     // 评论用户头像
                "nickname":"erhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "1234aaegaefgaafag1",  // string类型id
                "sec_openid":"kjabfjkgegegegegf",    // 评论用户的加密openid, 当前其实没有加密
                "content":"3",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/1a59df123cac3944d1104dd164160888.jpeg",     // 评论用户头像
                "nickname":"sanhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "1234aegaegeaegaaeg1",  // string类型id
                "sec_openid":"aaaaaaaaaaaa",    // 评论用户的加密openid, 当前其实没有加密
                "content":"nihao",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/391b8b23c018e957d38b6787f0791fa7.jpeg",     // 评论用户头像
                "nickname":"sihao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "12wrhrewgsasafegaeg1",  // string类型id
                "sec_openid":"bbbbtaekabbbbbb",    // 评论用户的加密openid, 当前其实没有加密
                "content":"3",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/a45f096821bb09659443c512c204ec47.jpeg",     // 评论用户头像
                "nickname":"wuhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "1234aegaeg1",  // string类型id
                "sec_openid":"cccabfjkcccccc",    // 评论用户的加密openid, 当前其实没有加密
                "content":"1",       // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"liuhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            }
        ]

        let sendArr = getRandomSubsetUnique(pinglunArr)

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  { arr: sendArr }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers);
    }

    function sendGiftRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/getGift`;

        let giftArr = [
            {
                "msg_id": "1029378912340134",  // string类型id
                "sec_openid":"kjabfjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "PJ0FFeaDzXUreuUBZH6Hs+b56Jh0tQjrq0bIrrlZmv13GSAL9Q1hf59fjGk=",  // 加密的礼物id
                "gift_num": 22,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"yihao",      // 评论用户昵称(不加密)
                "timestamp":1649068664, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "21372038947023",  // string类型id
                "sec_openid":"kjabfjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "gx7pmjQfhBaDOG2XkWI2peZ66YFWkCWRjZXpTqb23O/epru+sxWyTV/3Ufs=",  // 加密的礼物id
                "gift_num": 8,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"yihao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "230478232345234",  // string类型id
                "sec_openid":"aaaaafjkabef",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",  // 加密的礼物id
                "gift_num": 1,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分    // 评论内容
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/9c19c581f33e134b252d44dbc5ddef67.jpeg",     // 评论用户头像
                "nickname":"erhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "908098782397423",  // string类型id
                "sec_openid":"kjabfjkgegegegegf",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "28rYzVFNyXEXFC8HI+f/WG+I7a6lfl3OyZZjUS+CVuwCgYZrPrUdytGHu0c=",  // 加密的礼物id
                "gift_num": 2,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/1a59df123cac3944d1104dd164160888.jpeg",     // 评论用户头像
                "nickname":"sanhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "87312908470124",  // string类型id
                "sec_openid":"aaaaaaaaaaaa",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "P7zDZzpeO215SpUptB+aURb1+zC14UC9MY1+MHszKoF0p5gzYk8CNEbey60=",  // 加密的礼物id
                "gift_num": 3,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/391b8b23c018e957d38b6787f0791fa7.jpeg",     // 评论用户头像
                "nickname":"sihao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "23408230949028734234",  // string类型id
                "sec_openid":"bbbbtaekabbbbbb",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "PJ0FFeaDzXUreuUBZH6Hs+b56Jh0tQjrq0bIrrlZmv13GSAL9Q1hf59fjGk=",  // 加密的礼物id
                "gift_num": 2,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/a45f096821bb09659443c512c204ec47.jpeg",     // 评论用户头像
                "nickname":"wuhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            },
            {
                // 一样的用户多条不同组的评论
                "msg_id": "208347902834234",  // string类型id
                "sec_openid":"cccabfjkcccccc",    // 评论用户的加密openid, 当前其实没有加密
                "sec_gift_id": "IkkadLfz7O/a5UR45p/OOCCG6ewAWVbsuzR/Z+v1v76CBU+mTG/wPjqdpfg=",  // 加密的礼物id
                "gift_num": 1,        // 送出的礼物数量
                "gift_value": 10000,    // 礼物总价值，单位分
                "avatar_url":"https://blaze-api-test.xinghuohuiju.com/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg",     // 评论用户头像
                "nickname":"liuhao",      // 评论用户昵称(不加密)
                "timestamp":1649068964, // 评论毫秒级时间戳
            }
        ]

        let sendArr = getRandomSubsetUnique(giftArr)

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  { arr: sendArr }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers);
    }

    function sendFinishRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/finishGame`;

        let message = {
                "msg_id": "1029378912340134",  // string类型id
                "champion": 1,
                "finish_track_info": [
                    {
                        "track": 1,
                        "is_champion": 1,
                        "is_finish": 1,
                        "mileage": 100,
                        "jump_height": 8.5,
                        "finish_time": 105,  //完成时间
                        "fastest_speed": 20,    // 当局最快速度
                        "attack_power": 3,    // 当局的导弹次数
                        "game_mode": 3,    // 当局的游戏类型，从1开始
                    },
                    {
                        "track": 2,
                        "is_champion": 0,
                        "is_finish": 1,
                        "mileage": 100,
                        "jump_height": 3.65,
                        "finish_time": 0,  //完成时间
                        "fastest_speed": 22,    // 当局最快速度
                        "attack_power": 1,    // 当局的导弹次数
                        "game_mode": 3,    // 当局的游戏类型，从1开始
                    },
                    {
                        "track": 3,
                        "is_champion": 0,
                        "is_finish": 0,
                        "mileage": 70,
                        "jump_height": 5,
                        "finish_time": 180,  //完成时间
                        "fastest_speed": 15,    // 当局最快速度
                        "attack_power": 10,    // 当局的导弹次数
                        "game_mode": 3,    // 当局的游戏类型，从1开始
                    },
                ],        // 阵营完成信息
                "timestamp":1649068664, // 评论毫秒级时间戳
        }

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  message
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + liveRoomAuthToken,
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers);
    }

    function sendGetRanksRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/getRanks`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  {  }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
            'Authorization': 'Bearer ' + liveRoomAuthToken,
        };

        sendGetRequest(url, data, headers).then(res=>{

            console.log("sendGetRanksRequest function res : ", res)
            let resdata = JSON.parse(res)
            let scoreRank = resdata.data.ranks.score_rank
            let mileageRank = resdata.data.ranks.mileage_rank
            let jumpHeightRank = resdata.data.ranks.jump_height_rank
            // 三个数组结构一致
            // {
            //     "index": 1,      // 排名
            //     "user_id": "wejhrwiuehr",  // User id
            //     "user_name": "asegfhaeg",  // user name
            //     "head_img": "https://blaze-api-test.xinghuohuiju.com/static/a45f096821bb09659443c512c204ec47.jpeg",
                                    //  用户头像
            //     "level": 7,      // 用户登记
            //     "value": 922950      // 对应的排行数据，分数，里程，登高
            // }

            console.log("sendGetRanksRequest 3 ranks : ", scoreRank, mileageRank, jumpHeightRank)
        });
    }

    function sendGetWorldRecordsRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/getWorldRecords`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  {  }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
            'Authorization': 'Bearer ' + liveRoomAuthToken,
        };

        sendGetRequest(url, data, headers).then(res=>{
            console.log("sendGetRanksRequest function res : ", res, res.data, typeof res.data)
            let resdata = JSON.parse(res)
            console.log("sendGetRanksRequest function res 222 : ", resdata.data, typeof resdata.data)
            let fastest_speed = resdata.data.records.fastest_speed
            let finish_time = resdata.data.records.finish_time
            let finish_time1 = resdata.data.records.finish_time1
            let finish_time2 = resdata.data.records.finish_time2
            let jump_height = resdata.data.records.jump_height
            let attack_power = resdata.data.records.attack_power
            console.log("sendGetWorldRecordsRequest 6 num : ", fastest_speed
                , finish_time, finish_time1, finish_time2, jump_height, attack_power
                        )
        });
    }

    function openSendManyRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/OpenSendManyRequest`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  {
            "live_room_id": liveRoomID,
        }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{

        });
    }

    function openSendManyZanRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/OpenSendManyZanRequest`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  {
            "live_room_id": liveRoomID,
        }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{

        });
    }

    function closeSendManyRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/CloseSendManyRequest`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const data =  {
            "live_room_id": liveRoomID,
        }
        const headers = {
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        sendPostRequest(url, data, headers).then(res=>{

        });
    }

    function sendClientErrorRequest(){
        const url = httpRequestMethod + `://${ip}/api/v1/recordClientError`;

        const data =  {"live_room_id": "111",
            "desc": "this is desc",
            "env": "text ios env",
            "extra_s_1": "extra_s_1",
            "extra_s_2": "extra_s_2",
            "extra_s_3": "extra_s_3",
            "extra_s_4": "extra_s_4",
            "extra_s_5": "extra_s_5",
            "extra_i_1": 1,
            "extra_i_2": 2,
            "extra_i_3": 3,
            "extra_i_4": 4,
            "extra_i_5": 5
        }
        const headers = {
            'Content-Type': 'application/json',
        };

        sendPostRequest(url, data, headers).then(res=>{

        });
    }
    
    function sendManyRequest(){
        let giftNum = document.getElementById('giftNum').value;
        if(giftNum !='' && parseInt(giftNum)<=0){
            alert("礼物数量请填入数字")
            return
        }
        if(giftNum===''){
            giftNum = 1
            document.getElementById('giftNum').value = giftNum
        }
        for (let i = 0; i < giftNum; i++) {
            sendLikeMsg()
        }
    }

    // 存游戏数据
    function sendGameData(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/setGameData`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const gameData =  document.getElementById('gameData').value
        if(gameData==''){
            alert("请填写游戏数据")
            return
        }

        // 直播间id放在header中
        const headers = {
            'Authorization': 'Bearer ' + liveRoomAuthToken,
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        // 构造游戏数据，放到名为data的key中
        const data = {
            "data": gameData
        }

        sendPostRequest(url, data, headers).then(res=>{
            consoleText("发送游戏数据，获取res ：", res)
        });
    }

    // 取最新的游戏数据
    function getGameData(){
        const url = httpRequestMethod + `://${ip}/api/v1/auth/getGameData`;

        liveRoomID = document.getElementById('liveRoomId').value;
        if(liveRoomID == ''){
            alert("请填写直播间号")
            return
        }

        const headers = {
            'Authorization': 'Bearer ' + liveRoomAuthToken,
            'Content-Type': 'application/json',
            'x-roomid': liveRoomID,
        };

        const data = {}

        sendPostRequest(url, data, headers).then(res=>{
            consoleText("获取游戏数据，获取res ：", res, typeof res)
            resObj = JSON.parse(res)
            console.log("获取游戏数据，resObj.data ：", resObj.data)
            console.log("获取游戏数据，resObj.data.gameData ：", resObj.data.gameData)
            // 获取游戏数据的原始json字符串
            let gameDataStr = resObj.data.gameData.raw_data
            console.log("gameDataStr : ", gameDataStr)
            // 字符串转成对象,获得最终的游戏数据的对象
            let gameData = JSON.parse(gameDataStr)
            console.log("gameData : ", gameData)
        });
    }


    function sendGetRequest(url, params = {}, headers = {}) {
        return new Promise((resolve, reject) => {
            // 构造查询字符串
            const queryString = new URLSearchParams(params).toString();
            const fullUrl = `${url}?${queryString}`;

            // 创建一个新的 XMLHttpRequest 对象
            const xhr = new XMLHttpRequest();

            // 配置 GET 请求
            xhr.open('GET', fullUrl, true);

            // 设置请求头
            for (let key in headers) {
                xhr.setRequestHeader(key, headers[key]);
            }

            // 设置回调函数
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log('GET 请求成功:', xhr.responseText);
                    resolve(xhr.responseText); // 成功时，将响应内容传递给 resolve
                } else {
                    console.error('GET 请求失败:', xhr.statusText);
                    reject(new Error(xhr.statusText)); // 失败时，将错误传递给 reject
                }
            };

            xhr.onerror = function() {
                console.error('GET 请求发生错误');
                reject(new Error('请求发生错误')); // 网络错误等情况
            };

            // 发送请求
            xhr.send();
        });
    }

    function sendPostRequest(url, data = {}, headers = {}) {
        return new Promise((resolve, reject) => {
            // 创建一个新的 XMLHttpRequest 对象
            const xhr = new XMLHttpRequest();

            // 配置 POST 请求
            xhr.open('POST', url, true);

            console.log("before set headers");

            // 设置请求头
            for (let key in headers) {
                console.log("set headers:", key, headers[key]);
                xhr.setRequestHeader(key, headers[key]);
            }
            console.log("set headers over");

            // 设置回调函数
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log('POST 请求成功:', xhr.responseText);
                    resolve(xhr.responseText); // 成功时，将响应内容传递给 resolve
                } else {
                    console.error('POST 请求失败:', xhr.statusText);
                    reject(new Error(xhr.statusText)); // 失败时，将错误传递给 reject
                }
            };

            xhr.onerror = function() {
                console.error('POST 请求发生错误');
                reject(new Error('请求发生错误')); // 网络错误等情况
            };

            // 将数据转换为 JSON 格式（如果需要）
            const jsonData = JSON.stringify(data);

            // 发送请求
            xhr.send(jsonData);
        });

        function generateUUID() {
            return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
                (c ^ Math.random() * 16 >> c / 4).toString(16)
            );
        }
    }
</script>
</body>
</html>